package com.ternnetwork.batch.item.excel;


import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.batch.item.ExecutionContext;
import org.springframework.batch.item.ItemStream;
import org.springframework.batch.item.ItemStreamException;
import org.springframework.batch.item.ItemWriter;
import org.springframework.core.io.Resource;
import org.springframework.util.Assert;

import com.ternnetwork.batch.item.mapper.excel.ModelToExcelRowMapper;




/**
 * Excel文件写入
 * @author xuwenfeng
 *
 * @param <T>
 */
public class ExcelItemWriter <T> implements ItemWriter<T>, ItemStream{
	
	
	private static final Log log = LogFactory.getLog(ExcelItemWriter.class);
	
	

	private Resource resource;

	private String header;

	private int currentRowIndex = 0;

	private Workbook workbook;
	
	private Sheet sheet;
	
	private ModelToExcelRowMapper rowMapper;
	
	private static final String XLSX=".xlsx";
	
	private static final String XLS=".xls";
	@Override
	public void open(ExecutionContext executionContext) {
	
		Assert.notNull(resource, "The resource must be set");
		Assert.notNull(header, "The header must be set");
		Assert.notNull(rowMapper, "The rowMapper must be set");
		Assert.isTrue((resource.getFilename().endsWith(".xlsx")||resource.getFilename().endsWith(".xls")), "excel file name must be end with .xlsx or .xls");;
		
		if(resource.getFilename().endsWith(XLSX)){
			workbook =new XSSFWorkbook();
		}else if(resource.getFilename().endsWith(XLS)){
			workbook =new HSSFWorkbook();
		}
		
		sheet= (Sheet) workbook.createSheet("sheet0"); 
	    Row row=sheet.createRow(0);
		if(!StringUtils.isEmpty(header)){
			String[] headerArray=header.split(",");
			for (int j = 0; j < headerArray.length; j++) {  
                Cell cell = row.createCell(j);  
                cell.setCellValue(headerArray[j]);
            }  
		}
		currentRowIndex=currentRowIndex+1;
		try {
			File fileAbsolutePath=new File(resource.getFile().getAbsolutePath());
			if(!fileAbsolutePath.exists()){
				fileAbsolutePath.mkdirs();
			}
			log.info("生成excel文件:"+resource.getFilename());
			if(resource.getFile().exists()==true){
				resource.getFile().delete();//如果文件已经存在则先删除
			}
		
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	@Override
	public void write(List<? extends T> items) throws Exception {
		
		for(Object object:items){
			//进行模形与行的转换 
		    rowMapper.mapRow(object, sheet,workbook, currentRowIndex);
			currentRowIndex=currentRowIndex+1;
		}
	}

	

	@Override
	public void close() throws ItemStreamException {
		
		try {
			OutputStream outputStream = new FileOutputStream(resource.getFile(), true);
			
			workbook.write(outputStream);
			
			outputStream.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public void update(ExecutionContext executionContext) throws ItemStreamException {
		//executionContext.putLong(CURRENT_LOCATION, new Long(currentLocation).longValue());
	}

	public Resource getResource() {
		return resource;
	}

	public void setResource(Resource resource) {
		this.resource = resource;
	}

	public String getHeader() {
		return header;
	}

	public void setHeader(String header) {
		this.header = header;
	}

	public ModelToExcelRowMapper getRowMapper() {
		return rowMapper;
	}

	public void setRowMapper(ModelToExcelRowMapper rowMapper) {
		this.rowMapper = rowMapper;
	}

	

}
